//
//  DownLoadVC.m
//  doubleEduStudents
//
//  Created by 盛洋 on 2021/2/25.
//  Copyright © 2021 shengYang. All rights reserved.
//  这个页面逻辑写复杂了，后面的兄弟有时间可以重写

#import "DownLoadVC.h"
#import "downLoadCollectionViewCell1.h"
#import "downLoadCollectionCell2.h"
#import "MyWorkVC.h"
#import "MovEncodeToMpegTool.h"
#import "UpLoadImgModel.h"

@interface DownLoadVC ()<UICollectionViewDataSource,UICollectionViewDelegate,LGTextFieldDelegate,LGTextViewdDelegate,downLoadCollectionCell2Delegte,TZImagePickerControllerDelegate>

@property (strong, nonatomic) IBOutlet UICollectionView *collection_view;
@end

@implementation DownLoadVC
{
    NSMutableDictionary *parmaDic;
    RequestServices *service;
    NSMutableArray *fileList;//上传的图片url数组
    NSArray *chooseArr;//选择作品图片数组
    NSMutableArray *pictureArr;//确认选择作品图片数组
    NSMutableArray *urlArr;//上传的作品图片返回的url数组
    NSArray *videoArr;//返回视频数组
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"上传作品";
    [self addCollectionview];
    parmaDic = [NSMutableDictionary dictionary];
    pictureArr = [NSMutableArray array];
    videoArr = [NSArray array];
    urlArr = [NSMutableArray array];
    fileList = [NSMutableArray array];
    service = [[RequestServices alloc]initWithDelegate:self];
    [parmaDic setValue:@(self.type) forKey:@"type"];
    [parmaDic setValue:@(self.typeid) forKey:@"typeid"];

}

-(void)addCollectionview{
    self.collection_view.delegate = self;
    self.collection_view.dataSource = self;
    [self.collection_view registerNib:[UINib nibWithNibName:@"downLoadCollectionViewCell1" bundle:nil] forCellWithReuseIdentifier:@"downLoadCollectionViewCell1"];
    [self.collection_view registerNib:[UINib nibWithNibName:@"downLoadCollectionCell2" bundle:nil] forCellWithReuseIdentifier:@"downLoadCollectionCell2"];
    self.collection_view.showsHorizontalScrollIndicator = NO;
    self.collection_view.showsVerticalScrollIndicator = NO;

}

#pragma mark ----------------- collectionViewDataSource

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 2;
}


//每个item的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == 0) {
        return CGSizeMake(CollectionView_Width/2, CollectionView_Height*0.9);
    }else{
        return CGSizeMake(CollectionView_Width/1.1, CollectionView_Height * 0.9);
    }
}
//cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == 0) {
        downLoadCollectionViewCell1 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"downLoadCollectionViewCell1" forIndexPath:indexPath];
        cell.name_field.my_delegate = self;
        cell.jianjie_textView.my_delegate = self;
        //选择封面
        [cell.add_btn addTarget:self action:@selector(chsoosePicture:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else{
       downLoadCollectionCell2 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"downLoadCollectionCell2" forIndexPath:indexPath];
        cell.delegate = self;
        cell.pictureArr = [NSMutableArray arrayWithArray:pictureArr];
        cell.coverImg = parmaDic[@"cover"];
        [cell.downCollection_view reloadData];
        //提交作品
        [cell.tiJiao_btn addTarget:self action:@selector(tiJiaoZuopin) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}

//标题
-(void)LGtextFieldDidEndEditing:(UITextField *)textField{
    [parmaDic setValue:textField.text forKey:@"name"];
}

//简介
-(void)LGtextViewDidEndEditing:(UITextView *)textView{
    [parmaDic setValue:textView.text forKey:@"des"];
}

-(void)chsoosePicture:(UIButton *)sender{
    //1.判断相册是否可以打开
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        return;
    }
    //解决在6P上选取相册时取消按钮不好点击问题
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1  delegate:self];
    //是否允许选择视频
    imagePickerVc.allowPickingMultipleVideo = NO;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickerVc.naviTitleColor = [UIColor whiteColor];
    imagePickerVc.cancelBtnTitleStr = @"取消";
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos) {
            [sender setBackgroundImage:photos[0] forState:UIControlStateNormal];
            [self->parmaDic setValue:photos[0] forKey:@"photo"];
            [self->service upLoadFile:photos tag:8000];
            
        }
    }];
    
    [self.navigationController presentViewController:imagePickerVc animated:YES completion:nil];
}
#pragma mark ---------------- downLoadCollectionCell2Delegte

//上传作品图片
-(void)chooseWorkImg{
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9  delegate:self];
    //是否允许选择视频
    imagePickerVc.allowPickingMultipleVideo = NO;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickerVc.naviTitleColor = [UIColor whiteColor];
    imagePickerVc.cancelBtnTitleStr = @"取消";
    chooseArr = nil;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos) {
            //存在多次上传图片情况（比如一次传3张，一次传6张）
            self->chooseArr = [NSArray arrayWithArray:photos];
            
            [self->pictureArr addObjectsFromArray:self->chooseArr];
            if (self->pictureArr.count > 9) {
                [self ShowNewMsg:@"最多只能上传9张图片"];
                NSArray *arr = [self->pictureArr subarrayWithRange:NSMakeRange(0, 9)];
                self->pictureArr = [arr mutableCopy];
            }
            [self.collection_view reloadData];
        }
        /**
         * 上传作品
         */
        if (self->pictureArr.count>0) {
            [self->service upLoadFile:self->pictureArr tag:8001];
        }
    }];
    
    [self.navigationController presentViewController:imagePickerVc animated:YES completion:nil];
}
//删除作品
-(void)deletePicture:(UIButton *)sender{
    if (pictureArr.count > 0 && sender.tag < 4000) {
        NSInteger tag = sender.tag - 3002;
        [pictureArr removeObjectAtIndex:tag];
        [self.collection_view reloadData];
    }
}

//选择视频
-(void)chooseVideo{
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    //是否允许选择视频
    imagePickerVc.allowPickingMultipleVideo = YES;
    imagePickerVc.allowPickingImage = NO;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickerVc.naviTitleColor = [UIColor whiteColor];
    imagePickerVc.cancelBtnTitleStr = @"取消";
    [imagePickerVc setDidFinishPickingVideoHandle:^(UIImage *coverImage, PHAsset *asset) {
        [MovEncodeToMpegTool convertMovToMp4FromPHAsset:asset
                          andAVAssetExportPresetQuality:ExportPresetMediumQuality
                      andMovEncodeToMpegToolResultBlock:^(NSURL *mp4FileUrl, NSData *mp4Data, NSError *error) {
            NSLog(@"--------- 视频编码 ----------- 结束 ----------\n{\n  %@,\n   %ld,\n  %@\n}",mp4FileUrl,mp4Data.length,error.localizedDescription);
            [self->parmaDic setValue:mp4FileUrl forKey:@"video"];
            /**
             * 上传视频
             */
            self->service.view = self.view;
            [self->service requestUPLoadVideo:self->parmaDic[@"video"] tag:8002];
        }];
        [SVProgressHUD showWithStatus:@"视频上传中"];
        [self->parmaDic setValue:coverImage forKey:@"cover"];
        [self.collection_view reloadData];
    }];
    [self.navigationController presentViewController:imagePickerVc animated:YES completion:nil];
}

//删除视频
-(void)deleteVideo:(UIButton *)sender{
    if (sender.tag == 4000) {
        [parmaDic removeObjectsForKeys:@[@"video",@"cover"]];
        [self.collection_view reloadData];
    }
}


#pragma mark --------------------- requestDelegate
-(void)getFinished:(NSDictionary *)obj tag:(long long)tag{
    [self HideLoading];
    if (tag == 8000) {
        //获取上传封面图像url
        NSArray *faceArr = [UpLoadImgModel mj_objectArrayWithKeyValuesArray:obj];
        UpLoadImgModel *model = faceArr[0];
        [parmaDic setValue:model.url forKey:@"photo"];
    }
    
    if (tag == 8001) {
        NSLog(@"返回照片url--%@",obj);
        [urlArr removeAllObjects];//清空上一次选择的图片
        fileList = [UpLoadImgModel mj_objectArrayWithKeyValuesArray:obj];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        for (int i = 0; i<fileList.count; i++) {
            UpLoadImgModel *model = fileList[i];
            [dic setValue:model.url forKey:@"fileUrl"];
            [urlArr addObject:dic];
        }
        [parmaDic setValue:urlArr forKey:@"productfileidlist"];
    }
    
    if (tag == 8002) {
        NSLog(@"返回视频url--%@",obj);
        [SVProgressHUD showSuccessWithStatus:@"视频上传成功"];

        videoArr = [UpLoadImgModel mj_objectArrayWithKeyValuesArray:obj];
    }
    
    if (tag == 8003) {
        //提交作品成功
        [SVProgressHUD showSuccessWithStatus:@"提交作品成功"];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)getError:(NSError *)error tag:(long long)tag{
    [self HideLoading];
    [self ShowNewMsg:error.domain];
}

//提交作品
-(void)tiJiaoZuopin{
    
//    MyWorkVC *vc = [[MyWorkVC alloc]init];
//    [self PushToViewController:vc];
    //添加视频
    if (videoArr.count > 0) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        UpLoadImgModel *model = videoArr[0];
        [dic setValue:model.url forKey:@"fileUrl"];
        [urlArr addObject:dic];
        [parmaDic setValue:urlArr forKey:@"productfileidlist"];
    }
    NSLog(@"提交上传内容---%@----",parmaDic);
    service.view = self.view;
    [self.view endEditing:YES];
    [parmaDic removeObjectsForKeys:@[@"video",@"cover"]];
    [service requestUPLoad:parmaDic tag:8003];
}

//四周边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
